package com.yx.gsyd.controller.admin;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.gsyd.config.CustomCellWriteHandler;
import com.yx.gsyd.entity.SysJydz;
import com.yx.gsyd.entity.SysManager;
import com.yx.gsyd.entity.TaskList;
import com.yx.gsyd.entity.model.TasklistModel;
import com.yx.gsyd.entity.search.TaskListSearch;
import com.yx.gsyd.qpage.QPage;
import com.yx.gsyd.service.ISmsService;
import com.yx.gsyd.service.ISysManagerService;
import com.yx.gsyd.service.ITaskListService;
import com.yx.gsyd.util.CellStyleUtils;
import com.yx.gsyd.util.ResultView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-29
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/task-list")
public class TaskListController {

    @Autowired
    private ISysManagerService iSysManagerService;

    @Autowired
    private ITaskListService iTaskListService;

    @Autowired
    private ISmsService iSmsService;

    /**
     * 列表分页
     * @param obj
     * @return
     */
    @GetMapping("/getPageList")
    public ResultView getPageList(QPage qPage, TaskListSearch obj) {
        SysManager sysManager=this.iSysManagerService.getById(StpUtil.getLoginIdAsString());
        //账号类型1.管理员，2.服务中心员工，3数据团队，4.交互团队，5.银行团队6.员工
        if(sysManager.getMType()==1||sysManager.getMType()==3){
            System.out.println("全部权限");
        }else{
            if(sysManager.getMType()==2){
                obj.setFwzxzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==4){
                obj.setJhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==5){
                obj.setYhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==6){
                SysManager parent=this.iSysManagerService.getById(sysManager.getParentManagerId());
                if(parent.getMType()==2){
                    obj.setFwzxygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==4){
                    obj.setJhtdygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==5){
                    obj.setYhtdygManagerId(sysManager.getManagerId());
                }
            }
        }
        return this.iTaskListService.getPageList(qPage,obj);
    }


    /**
     * 分配
     * @param taskId
     * @param mname
     * @return
     */
    @PostMapping("/fenpei")
    public ResultView fenpei(String taskId,String mname,String mname2) {
        return this.iTaskListService.fenpei(taskId,mname,mname2);
    }

    /**
     * 删除
     * @param taskId
     * @return
     */
    @PostMapping("/del")
    public ResultView del(String taskId) {
        return this.iTaskListService.del(taskId);
    }

    /**
     * 退件
     * @param taskId
     * @param applyContent
     * @return
     */
    @PostMapping("/tuijian")
    public ResultView tuijian(String taskId,String applyContent) {
        return this.iTaskListService.tuijian(taskId,applyContent);
    }


    /**
     * 分配-银行专属
     * @param taskId 业务ID
     * @param applyStatus 1.通过，2.拒绝
     * @param applyContent 通过的金额或者拒绝的理由
     * @return
     */
    @PostMapping("/wanjie")
    public ResultView wanjie(String taskId,String applyStatus,String applyContent,String applyMoney) {
        TaskList taskList=this.iTaskListService.getById(taskId);
        if(taskList.getStatus()==4){
            return ResultView.error("数据已完结，无法重复操作");
        }
        taskList.setApplyStatus(applyStatus);
        if(applyStatus.equals("1")){
            taskList.setApplyMoney(new BigDecimal(applyMoney));
        }else{
            taskList.setApplyContent(applyContent);
            //发送短信提醒哥哥
            if(!taskList.getSoureData().equals("系统")){
                if(StringUtils.isNotBlank(taskList.getSoureManagerId())){
                    SysManager sysManager=this.iSysManagerService.getById(taskList.getManagerId());
                    if(sysManager!=null&&sysManager.getMAccount().length()==11){
                        iSmsService.SendSmsQy(sysManager.getMAccount(),sysManager.getMName(),taskList.getGsmc());
                    }else{
                        log.error("手机号不符合规则，不推送{"+sysManager.getMAccount()+"}");
                    }
                }else{
                    String soureDate=taskList.getSoureData();
                    QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("m_name",soureDate);
                    List<SysManager> sysManagers=this.iSysManagerService.list(queryWrapper);
                    if(sysManagers!=null&&sysManagers.size()>=1){
                        SysManager sysManager=sysManagers.get(0);
                        if(sysManager!=null&&sysManager.getMAccount().length()==11){
                            iSmsService.SendSmsQy(sysManager.getMAccount(),sysManager.getMName(),taskList.getGsmc());
                        }else{
                            log.error("手机号不符合规则，不推送{"+sysManager.getMAccount()+"}");
                        }
                    }else{
                        log.error("账号没找到，不推送{"+taskList.getTaskId()+"}");
                    }
                }
            }else{
                log.error("二维码来自系统数据，不推送{"+taskList.getTaskId()+"}");
            }
        }
        taskList.setStatus(4);
        this.iTaskListService.updateById(taskList);
        return ResultView.ok();
    }


    /**
     * 分配-银行专属
     * @param taskId 业务ID
     * @return
     */
    @PostMapping("/wanjieNew")
    public ResultView wanjieNew(String taskId,String setup,String setcontentone,String setcontenttwo,String setcontentthree
            ,String setcontentfour,String setcontentfive,String setcontentsex,String setcontentqi
            ,String setcontentba,String setcontentjiu,String setcontentsexshi,String setcontentsexshiyi,String setcontentshier
            ,String setcontentshisan,String setcontentshisi,String setcontentsiwu,String setcontentsiliu,String setcontentsiqi) {
        TaskList taskList=this.iTaskListService.getById(taskId);
        if(taskList.getStatus()==4){
            return ResultView.error("数据已完结，无法重复操作");
        }
        if(StringUtils.isNotBlank(setcontentone)){
            if(setcontentone.equals("拒绝")){
                taskList.setStatus(4);
                //发送短信提醒哥哥
                if(!taskList.getSoureData().equals("系统")){
                    if(StringUtils.isNotBlank(taskList.getSoureManagerId())){
                        SysManager sysManager=this.iSysManagerService.getById(taskList.getManagerId());
                        if(sysManager!=null&&sysManager.getMAccount().length()==11){
                            iSmsService.SendSmsQy(sysManager.getMAccount(),sysManager.getMName(),taskList.getGsmc());
                        }else{
                            log.error("手机号不符合规则，不推送{"+sysManager.getMAccount()+"}");
                        }
                    }else{
                        String soureDate=taskList.getSoureData();
                        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
                        queryWrapper.eq("m_name",soureDate);
                        List<SysManager> sysManagers=this.iSysManagerService.list(queryWrapper);
                        if(sysManagers!=null&&sysManagers.size()>=1){
                            SysManager sysManager=sysManagers.get(0);
                            if(sysManager!=null&&sysManager.getMAccount().length()==11){
                                iSmsService.SendSmsQy(sysManager.getMAccount(),sysManager.getMName(),taskList.getGsmc());
                            }else{
                                log.error("手机号不符合规则，不推送{"+sysManager.getMAccount()+"}");
                            }
                        }else{
                            log.error("账号没找到，不推送{"+taskList.getTaskId()+"}");
                        }
                    }
                }else{
                    log.error("二维码来自系统数据，不推送{"+taskList.getTaskId()+"}");
                }
            }
            taskList.setSetcontentone(setcontentone);
        }
        if(StringUtils.isNotBlank(setcontenttwo)){
            taskList.setSetcontenttwo(setcontenttwo);
        }
        if(StringUtils.isNotBlank(setcontentthree)){
            taskList.setSetcontentthree(setcontentthree);
        }
        if(StringUtils.isNotBlank(setcontentfour)){
            taskList.setSetcontentfour(setcontentfour);
        }

        if(StringUtils.isNotBlank(setcontentfive)){
            taskList.setSetcontentfive(setcontentfive);
        }
        if(StringUtils.isNotBlank(setcontentsex)){
            taskList.setSetcontentsex(setcontentsex);
        }
        if(StringUtils.isNotBlank(setcontentqi)){
            taskList.setSetcontentqi(setcontentqi);
        }
        if(StringUtils.isNotBlank(setcontentba)){
            taskList.setSetcontentba(setcontentba);
        }
        if(StringUtils.isNotBlank(setcontentjiu)){
            taskList.setSetcontentjiu(setcontentjiu);
        }
        if(StringUtils.isNotBlank(setcontentsexshi)){
            taskList.setSetcontentsexshi(setcontentsexshi);
        }
        if(StringUtils.isNotBlank(setcontentsexshiyi)){
            taskList.setSetcontentsexshiyi(setcontentsexshiyi);
        }
        if(StringUtils.isNotBlank(setcontentshier)){
            taskList.setSetcontentshier(setcontentshier);
        }
        if(StringUtils.isNotBlank(setcontentshisan)){
            taskList.setSetcontentshisan(setcontentshisan);
        }
        if(StringUtils.isNotBlank(setcontentshisi)){
            taskList.setSetcontentshisi(setcontentshisi);
        }
        if(StringUtils.isNotBlank(setcontentsiwu)){
            taskList.setSetcontentsiwu(setcontentsiwu);
        }
        if(StringUtils.isNotBlank(setcontentsiliu)){
            taskList.setSetcontentsiliu(setcontentsiliu);
        }
        if(StringUtils.isNotBlank(setcontentsiqi)){
            taskList.setSetcontentsiqi(setcontentsiqi);
        }
        int setcount=taskList.getSetup()+1;
        if(setcount==7){
            taskList.setStatus(4);
            taskList.setSetup(7);
        }else{
            taskList.setSetup(setcount);
        }
        this.iTaskListService.updateById(taskList);
        return ResultView.ok();
    }



    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @PostMapping("download")
    public void downloadFailedUsingJson(TaskListSearch obj, HttpServletResponse response) throws IOException {
        SysManager sysManager=this.iSysManagerService.getById(StpUtil.getLoginIdAsString());
        if(sysManager.getMType()==1||sysManager.getMType()==3){
            System.out.println("全部权限");
        }else{
            if(sysManager.getMType()==2){
                obj.setFwzxzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==4){
                obj.setJhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==5){
                obj.setYhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==6){
                SysManager parent=this.iSysManagerService.getById(sysManager.getParentManagerId());
                if(parent.getMType()==2){
                    obj.setFwzxygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==4){
                    obj.setJhtdygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==5){
                    obj.setYhtdygManagerId(sysManager.getManagerId());
                }
            }
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("信息列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<TasklistModel> deviceList=this.iTaskListService.downLoadList(obj);
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), TasklistModel.class).
                    autoCloseStream(Boolean.FALSE).
                    sheet("信息列表").registerWriteHandler(CellStyleUtils.getHorizontalCellStyleStrategy())
                    .registerWriteHandler(new CustomCellWriteHandler())
                    .doWrite(deviceList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }



}
